package com.db.patterns;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import cm.db.patterns.commands.Command;

import com.db.patterns.caches.Cache;
import com.db.patterns.caches.MapCache;
import com.db.patterns.client.RemoteServerCache;
import com.db.patterns.client.UpdatableCache;
import com.db.patterns.server.CacheListener;
import com.db.patterns.server.ClientListener;
import com.db.patterns.server.PublishCache;
import com.db.patterns.server.RemoteClientCache;

public class Main {
	static final int N = 100;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		PublishCache serverCache = new PublishCache(new MapCache());
		ClientListener clientListener = new ClientListener();
		serverCache.addListener(clientListener);
		
		BlockingQueue<Command> queue1 = new ArrayBlockingQueue<>(10);
		BlockingQueue<Command> queue2 = new ArrayBlockingQueue<>(10);
		
		clientListener.addClient(new RemoteClientCache(queue1));
		clientListener.addClient(new RemoteClientCache(queue2));
		
		UpdatableCache clientCache1 = new UpdatableCache(new MapCache(), new RemoteServerCache(queue1));
		UpdatableCache clientCache2 = new UpdatableCache(new MapCache(), new RemoteServerCache(queue2));
		
		clientCache1.start();
		clientCache2.start();
		
		for (int i=1; i<=N; i++)
			serverCache.put(String.valueOf(i), i);
		
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		for (int i=1; i<=N; i++) {
			System.out.println("1: " + clientCache1.get(String.valueOf(i)));
			System.out.println("2: " + clientCache2.get(String.valueOf(i)));
		}
		
		serverCache.put("1", 1000);
		System.out.println("1: " + clientCache1.get(String.valueOf(1)));
		System.out.println("2: " + clientCache2.get(String.valueOf(1)));

		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("1: " + clientCache1.get(String.valueOf(1)));
		System.out.println("2: " + clientCache2.get(String.valueOf(1)));
		
		serverCache.stop();
		
		clientCache1.stop();
		clientCache2.stop();
	}

}
